package com.itheima.thread.等待唤醒机制.送奶工案例;

public class Demo {
    public static void main(String[] args) {
        //创建奶箱对象
        Box box = new Box();
        //创建生产者线程并启动
        new Thread(() -> {
            int count = 0;
            while (true){
                synchronized ("desk"){
                    System.out.println("送奶工行动...");
                    if (box.getCount() == 0){
                        System.out.println("任务结束");
                        break;
                    }else {
                        //判断桌子上是否有数据
                        if (box.isFlag()){
                            System.out.println("奶箱已存在,等待消费者取货");
                            try {
                                "desk".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else {
                            System.out.println("送奶工正在送第" + (++count) + "瓶奶");
                            box.setFlag(true);
                            System.out.println("唤醒消费者");
                            "desk".notify();
                        }
                    }
                }
            }
        }).start();
        //创建消费者线程并启动
        new Thread(() -> {
            int count = 0;
            while (true){
                synchronized ("desk"){
                    System.out.println("消费者行动...");
                    if (box.getCount() == 0){
                        System.out.println("消费者结算");
                        break;
                    }else {
                        //判断桌子上是否有汉堡
                        if(box.isFlag()){
                            //有
                            box.countSubtract();
                            System.out.println("消费者正在取"+(++count) + "瓶奶");
                            box.setFlag(false);
                            System.out.println("唤醒送奶工");
                            "desk".notify();
                        }else {
                            //没有
                            System.out.println("等待送奶工");
                            try {
                                "desk".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }).start();
    }

}
